package com.financing.platform.util;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import org.apache.log4j.Logger;

import sun.misc.BASE64Encoder;

public class SecureUtil {
	static Logger log = Logger.getLogger(SecureUtil.class);
	
	public static String MD5EncryptAndBase64(String str){
		MessageDigest md = null;
		BASE64Encoder baseEncoder =new BASE64Encoder();
		
		if(StringUtil.isNullOrEmptyStr(str)){
			return null;
		}
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			log.error("MD5 Encrypt error",e);
			return null;
		}
		
		str = str+"fa123";
		
		return baseEncoder.encode(md.digest(str.getBytes()));
	}
	static String[] zm="a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z".split(",");
	public static String getRandom(int i){
		String random="";
		for (int j = 0; j < i; j++) {
			random+=zm[new Random().nextInt(zm.length)];
		}
		return random;
	}
	public static String encodeBase64(String str){
		String ret;
		try {
			BASE64Encoder baseEncoder =new BASE64Encoder();
			ret = baseEncoder.encode(str.getBytes());
			return getRandom(10)+URLEncoder.encode(ret,"utf-8");
		} catch (Exception e) {
			log.error("encodeBase64 error",e);
		}
		return str;
	}
	
	public static void main(String[] args) {
		System.out.println(MD5EncryptAndBase64("fa123!@#?><"));
	}
}
